/**
 * Copyright 2007-2008 Vidar Svansson
 *     
 * This file is part of JAdapter.
 * 
 * JAdapter is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * JAdapter is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with JAdapter.  If not, see <http://www.gnu.org/licenses/>.
 */
package org.jadapter.graph;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * 
 * @author Vidar Svansson
 * @since 0.1
 *
 * @param <T>
 * @param <U>
 */
public class Graph<T,U> {
    
    private Map<T,Map<T,U>> bitmap;    
    
    private int nodeCount = 0;
    
    public Graph() {
        this(new HashMap<T,Map<T,U>>()); 
    }
    
    public Graph(Map<T,Map<T,U>> bitmap) {
        this.bitmap = bitmap;
    }
    
    
	public void insert(T x, T y, U edge) {
		put(x, y, edge);
	}
    
    public final Iterable<T> from(T t) {
        return bitmap.get(t).keySet();
    }
    
    public final Iterable<T> to(T t) {
        Map<T, U> q = bitmap.get(t);
        if(q == null) return new ArrayList<T>();
        
        List<T> list = new ArrayList<T>(bitmap.get(t).size());
        for (T key : bitmap.keySet()) {
            if (bitmap.get(key).get(t) != null) list.add(key);
        }
        return list;
    }
               
    
    public final U get(T from, T to) {             
        if (!bitmap.containsKey(to)) {
            bitmap.put(to, new HashMap<T,U>());
        }
        
        Map<T,U> toRow = bitmap.get(from);
        if(toRow == null) {
            bitmap.put(from, new HashMap<T,U>());
            return null;
        }
        return toRow.get(to);
        
    }


    public final int size() {
        return nodeCount;
    }    
    
    protected final boolean put(T from, T to, U u) {
        if (get(from, to) == null) {
            bitmap.get(from).put(to, u);
            nodeCount++; 
            return true;
        }       
        return false;
    }

}
